package com.eight.cloud.springmvc.config;

import com.eight.cloud.redisson.utils.TokenManager;
import com.eight.cloud.springmvc.interceptor.TokenArgumentResolver;
import com.eight.cloud.springmvc.interceptor.UserInfoInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: MvcConfig
 * @Author: TXC
 * @Date: 2024-10-08 23:04
 **/
@Configuration
@ConditionalOnClass(DispatcherServlet.class)
public class MvcConfig implements WebMvcConfigurer {
    @Resource
    private TokenManager tokenManager;
    @Value("${spring.mvc.cors.origins:*}")
    private String[] origins;
    /**
     * UserContext方式获取用户信息
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new UserInfoInterceptor(tokenManager));
    }

    /**
     * 支持controller层用参数接受用户信息
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new TokenArgumentResolver(tokenManager));
    }

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //添加映射路径
        registry.addMapping("/**")
                //设置允许跨域的域名，*代表全部允许
                .allowedOrigins(origins)
                //是否发送Cookie
                .allowCredentials(false)
                //设置放行哪些原始域
                .allowedOriginPatterns("*")
                //放行哪些请求方式
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                //放行哪些原始请求头部信息
                .allowedHeaders("*")
                //暴露哪些原始请求头部信息
                .exposedHeaders("*");
    }
}
